package com.bluesky.jwf.component.tab;

import java.util.ArrayList;
import java.util.List;

import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.jwf.ComponentFactory;
import com.bluesky.jwf.component.Component;
import com.bluesky.jwf.component.event.EventHandler;
import com.bluesky.jwf.component.list.ListView;

/**
 * Tab is a tabbed sheets component. every tab has a title and a panel as its
 * body, but only one tab is visible at any time.
 * 
 * @author jack
 * 
 */
public class Tabs extends Component {
	private ListView titleListView;
	private Tag contentTag;
	private List<Tab> tabList;
	private int activeIndex;

	public Tabs() {
		tabList = new ArrayList<Tab>();
		activeIndex = -1;
	}

	@Override
	public void init(String html) {

		super.init(html);

		Tag titleTag = loadByJwfClass("title");
		titleListView = (ListView) ComponentFactory.getInstance()
				.createComponent(ListView.class.getSimpleName(),
						titleTag.toHtml());
		titleListView.setItemClass(TitleListItem.class);

		titleTag.replace(titleListView);

		contentTag = loadByJwfClass("content");

		refresh();
	}

	public void addTab(Tab tab) {
		tabList.add(tab);
		tab.setTabs(this);

		setActiveTab(tab);

	}

	public Tab addTab(String name, Tag content) {
		Tab tab = new Tab(name, content);
		addTab(tab);

		return tab;
	}

	public Tab getTab(int index) {
		return tabList.get(index);
	}

	public void removeTab(Tab tab) {
		tabList.remove(tab);
		// set a new active tab, index 0;
		if (!tabList.isEmpty()) {
			this.activeIndex = 0;
			tabList.get(activeIndex).setActive(true);
		} else
			activeIndex = -1;

		refresh();
	}

	public void removeTab(int index) {
		tabList.remove(index);

		// set a new active tab, index 0;
		if (!tabList.isEmpty()) {
			this.activeIndex = 0;
			tabList.get(activeIndex).setActive(true);
		} else
			activeIndex = -1;

		refresh();
	}

	public void setActiveTab(Tab tab) {
		int i = tabList.indexOf(tab);

		setActiveTab(i);
	}

	public void setActiveTab(int index) {
		this.activeIndex = index;

		for (int i = 0; i < tabList.size(); i++) {
			Tab t = tabList.get(i);

			t.setActive(i == index);
		}

		refresh();
	}

	protected void refresh() {
		titleListView.setModel(tabList);
		titleListView.dataBind();

		contentTag.removeAllChildren();
		if (activeIndex >= 0) {
			contentTag.addChild(tabList.get(activeIndex).getContent());
		}
	}

}
